namespace LightBox.Installer
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Security.Permissions;
    using System.Web;

    using LightBox.Properties;

    /// <summary>
    /// 
    /// </summary>
    sealed class LightboxInstall
    {
        private static string[] scripts = new string[] { Resources.PrototypeScript, Resources.ScriptaculousScript, Resources.LightboxScript };
        private static List<IInstaller> installers = LoadInstallers();

        /// <summary>
        /// 
        /// </summary>
        private LightboxInstall() { }

        /// <summary>
        /// 
        /// </summary>
        private static string LightBoxDirectory
        {
            get { return HttpContext.Current.Server.MapPath(string.Format("~/{0}", Resources.LightboxBaseFolder)); }
        }

        /// <summary>
        /// 
        /// </summary>
        public static string[] Scripts
        {
            get { return scripts; }
        }

        /// <summary>
        /// 
        /// </summary>
        public static void InstallFiles()
        {
            if (!Directory.Exists(LightBoxDirectory))
            {
                string path = LightBoxDirectory;
                FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.Write, path);
                perm.Demand();

                DirectoryInfo lightboxDir = Directory.CreateDirectory(LightBoxDirectory);

                List<IInstaller> installers = LoadInstallers();
                foreach (IInstaller installer in installers)
                {
                    installer.Install(path);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private static List<IInstaller> LoadInstallers()
        {
            List<IInstaller> installers = new List<IInstaller>();

            Type[] types = typeof(LightboxInstall).Assembly.GetTypes();
            Type installerType = typeof(IInstaller);

            foreach (Type t in types)
            {
                if (installerType.IsAssignableFrom(t) && !t.Equals(installerType))
                {
                    IInstaller installer = (IInstaller)Activator.CreateInstance(t);
                    installers.Add(installer);
                }
            }

            return installers;
        }
    }
}